package org.geektimes.projects.user.web.listener;

import org.eclipse.microprofile.config.ConfigProvider;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.management.UserManager;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.nio.charset.Charset;
import java.util.logging.Logger;

/**
 * 测试用途
 */
public class TestingListener implements ServletContextListener {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    public void contextInitialized(ServletContextEvent sce) {
//        ComponentContext context = ComponentContext.getInstance();
//        DBConnectionManager dbConnectionManager = context.getComponent("bean/DBConnectionManager");
//        dbConnectionManager.getConnection();
////        testUser(dbConnectionManager.getEntityManager());
//        logger.info("所有的 JNDI 组件名称：[");
//        context.getComponentNames().forEach(logger::info);
//        logger.info("]");

        // testReadingConfigurationFile();


        testConfiguration();
    }

    private void testReadingConfigurationFile() {
        String filepath = "META-INF/microprofile-config.properties";
        try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filepath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("当前读取到的行内容是：>>>>>>>>>" + line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    private void testConfiguration() {
        String appName = ConfigProvider.getConfig().getValue("application.name", String.class);
        //FIXME get null? why
        // microprofile-config.properties 这个鬼文件位置放错了。。。 debug了真是有半天.......
        // coding 5 分钟， debug 两小时.... 惨痛教训!!!
        System.out.println("the application_name is >>>>>>>: [ " + appName + " ]");

        double bookPrice = ConfigProvider.getConfig().getValue("book.price", Double.class);
        System.out.println("the book price is >>>>>>: [" + bookPrice + "]");
    }

    @Deprecated
    private void testJMX() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException, InterruptedException {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // jolikia 是 namespace
        ObjectName objectName = new ObjectName("jolokia:type=User");
        User user = new User();
        mBeanServer.registerMBean(new UserManager(user), objectName);

        while (true) {
            Thread.sleep(2000);
            logger.info(user.toString());
        }
    }

    @Deprecated
    private void testUser(EntityManager entityManager) {
        User user = new User();
        user.setName("小马哥");
        user.setPassword("******");
        user.setEmail("mercyblitz@gmail.com");
        user.setPhoneNumber("abcdefg");
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.persist(user);
        transaction.commit();
        System.out.println(entityManager.find(User.class, user.getId()));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

}
